import React, { FC, Suspense } from 'react';
import {
  FormPanel,
  type FormPanelObject,
  FormPanelStatus,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
  InputType,
  RuleType,
  Utils,
} from 'lfun-bg-comp';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { Button, Cascader, Col, Row, message } from 'antd';
import dayjs from 'dayjs';
import _ from 'lodash';
import { YES_NO } from '@/constant/basicOptions';
import styles from './index.less';
import { countries } from '@/constant/country';
import { ETHNICITIES } from '@/constant/ethnicity';
import { POLITICAL_STATUS } from '@/constant/studentOptions';
import {
  EDUCATION_NAME,
  HEALTH_STATUS,
  HIGHEST_EDUCATION,
  HIGHEST_EDUCATION_LEVEL,
  HMOTF_TYPE,
  HUKOU_TYPE,
  INFORMATION_APPLY_ABILITY,
  LANGUAGE,
  LANGUAGE_CERTIFICATE_NAMES,
  MAIN_TEACHING_LEVEL_TYPE,
  MARITAL_STATUS,
  POSITION_LEVEL,
  POSITION_TYPE,
  PROFESSIONAL_TECHNICAL_POSITION,
  PROFICIENCY,
  RECRUITMENT_WAY,
  SINGIN_CONTRACT_TYPE,
  STAFFING_ARRANGEMENT,
  STAFF_SOURCE,
  STAFF_TYPE,
} from '@/constant/teachOptions';
import { getCourseOptions, getProvinceCityCascader, searchOrgs } from '@/service/options';

export const formTpl = [
  {
    title: '基本信息',
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
    inputs: [
      {
        label: '国家/地区',
        name: 'nationality',
        key: 'nationality',
        required: true,
        inputType: InputType.select,
        relationFields: ['ethnicity', 'politicalStatus'],
        renderOption: countries,
      },
      {
        label: '民族',
        name: 'ethnicity',
        key: 'ethnicity',
        required: true,
        inputType: InputType.select,
        hidden: (form: FormPanelObject) => {
          return form.getFieldValue('nationality') !== 'CN';
        },
        renderOption: ETHNICITIES,
      },
      {
        label: '政治面貌',
        name: 'political_status',
        key: 'political_status',
        inputType: InputType.select,
        required: true,
        hidden: (form: FormPanelObject) => {
          console.log('🚀 ~ values:', form.getFieldsValue());
          return form.getFieldValue('nationality') !== 'CN';
        },
        renderOption: POLITICAL_STATUS,
      },
      {
        label: '籍贯',
        name: 'native_place',
        key: 'native_place',
        textRange: [0, 20],
      },
      {
        label: '出生地',
        name: 'birth_place',
        key: 'birth_place',
        textRange: [0, 20],
      },
      {
        label: '曾用名',
        name: 'former_name',
        key: 'former_name',
        textRange: [0, 20],
      },
      {
        label: '婚姻状况',
        name: 'marital_status',
        key: 'marital_status',
        required: true,
        inputType: InputType.select,
        renderOption: MARITAL_STATUS,
      },
      {
        label: '健康状况',
        name: 'health_condition',
        key: 'health_condition',
        inputType: InputType.children,
        children: <Cascader />,
        renderOption: HEALTH_STATUS,
      },
      {
        label: '最高学历',
        name: 'highest_education',
        key: 'highest_education',
        inputType: InputType.children,
        children: <Cascader />,
        renderOption: HIGHEST_EDUCATION,
      },
      {
        label: '获得最高学历的院校或机构',
        name: 'institution_of_highest_education',
        key: 'institution_of_highest_education',
        textRange: [0, 20],
      },
      {
        label: '从始特教开始年月',
        name: 'special_education_start_time',
        key: 'special_education_start_time',
        required: true,
        inputType: InputType.date,
        inputProps: {
          picker: 'month',
        },
      },
      {
        label: '参加工作年月',
        name: 'start_working_date',
        key: 'start_working_date',
        required: true,
        inputType: InputType.date,
        inputProps: {
          picker: 'month',
        },
        // formatSubmitValue: (value: any) => {
        //   if (value && value.isValid && value.isValid()) return value.format('YYYY-MM');
        //   return value;
        // },
      },
      {
        label: '户口所在地',
        name: 'hukou_type',
        key: 'hukou_type',
        inputType: InputType.select,
        renderOption: HUKOU_TYPE,
      },
      {
        label: '户口性质',
        name: 'hukou_type',
        key: 'hukou_type',
        inputType: InputType.select,
        renderOption: HUKOU_TYPE,
      },
      {
        label: '通讯地址省市县',
        name: 'contact_address',
        key: 'contact_address',
        inputType: InputType.cascader,
        renderOption: getProvinceCityCascader,
        formatSubmitValue: v => {
          if (_.isArray(v)) return v.join(',');
          return v;
        },
      },
      {
        label: '进本学校年月',
        name: 'enter_school_time',
        key: 'enter_school_time',
        required: true,
        inputType: InputType.date,
        inputProps: {
          picker: 'month',
        },
        // formatSubmitValue: (value: any) => {
        //   if (value && value.isValid && value.isValid()) return value.format('YYYY-MM');
        //   return value;
        // },
      },
      {
        label: '教职工来源',
        name: 'source_of_staff',
        key: 'source_of_staff',
        required: true,
        inputType: InputType.children,
        children: <Cascader />,
        renderOption: STAFF_SOURCE,
      },
      {
        label: '教职工类别',
        name: 'staff_category',
        key: 'staff_category',
        required: true,
        inputType: InputType.select,
        renderOption: () => {
          if (Utils.getProps('edu_type') === 'vocational') {
            return STAFF_TYPE.ZZ;
          }
          if (Utils.getProps('edu_type') === 'kg') {
            return STAFF_TYPE.KG;
          }
          // todo: 这里要区分学校类型数据
          return STAFF_TYPE.ZXX;
        },
      },
      {
        label: '是否在编',
        name: 'in_post',
        key: 'in_post',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '用人形式',
        name: 'employment_form',
        key: 'employment_form',
        required: true,
        inputType: InputType.select,
        renderOption: STAFFING_ARRANGEMENT,
      },
      {
        label: '签订合同情况',
        name: 'contract_signing_status',
        key: 'contract_signing_status',
        inputType: InputType.select,
        required: true,
        renderOption: SINGIN_CONTRACT_TYPE,
      },
      {
        label: '现任岗位类型',
        name: 'current_post_type',
        key: 'current_post_type',
        inputType: InputType.children,
        children: <Cascader />,
        renderOption: POSITION_TYPE, //TODO:类型无
      },
      {
        label: '现任岗位等级',
        name: 'current_post_level',
        key: 'current_post_level',
        inputType: InputType.children,
        children: <Cascader />,
        renderOption: POSITION_LEVEL,
      },
      {
        label: '现任专业技术职务',
        name: 'current_technical_position',
        key: 'current_technical_position',
        inputType: InputType.select,
        required: true,
        renderOption: PROFESSIONAL_TECHNICAL_POSITION,
      },

      {
        label: '户口类别',
        name: 'hukou_type',
        key: 'hukou_type',
        inputType: InputType.select,
        renderOption: HUKOU_TYPE,
      },
      {
        label: '港澳台侨外',
        name: 'hmotf',
        key: 'hmotf',
        inputType: InputType.select,
        renderOption: HMOTF_TYPE,
      },

      {
        label: '最高学历层次',
        name: 'highest_education_level',
        key: 'highest_education_level',
        inputType: InputType.select,
        renderOption: HIGHEST_EDUCATION_LEVEL,
      },

      {
        label: '最高学位名称',
        name: 'highest_degree_name',
        key: 'highest_degree_name',
        required: true,
        inputType: InputType.cascader,
        renderOption: EDUCATION_NAME,
        formatSubmitValue: (value: any) => {
          if (value && value.length && value.length > 0) {
            return value.join(',');
          }
          return value;
        },
        formatValue: value => {
          if (value && typeof value === 'string') {
            return value.split(',');
          }
          return value;
        },
      },

      {
        label: '主要任课学段',
        name: 'main_teaching_level',
        key: 'main_teaching_level',
        inputType: InputType.select,
        renderOption: MAIN_TEACHING_LEVEL_TYPE,
      },
      {
        label: '教师资格证编号',
        name: 'teacher_qualification_cert_num',
        key: 'teacher_qualification_cert_num',
        ruleType: RuleType.number,
        textRenge: [0, 50],
      },
      {
        label: '任教学科',
        name: 'teaching_discipline',
        key: 'teaching_discipline',
        inputType: InputType.select,
        renderOption: getCourseOptions,
      },
      {
        label: '语种',
        name: 'language',
        key: 'language',
        inputType: InputType.select,
        renderOption: LANGUAGE,
      },
      {
        label: '语言掌握程度',
        name: 'language_proficiency_level',
        key: 'language_proficiency_level',
        inputType: InputType.select,
        renderOption: PROFICIENCY,
      },
      {
        label: '语言证书名称',
        name: 'language_certificate_name',
        key: 'language_certificate_name',
        inputType: InputType.select,
        renderOption: LANGUAGE_CERTIFICATE_NAMES,
      },
      {
        label: '身份证件有效期',
        name: 'id_card_validity_period',
        key: 'id_card_validity_period',
        textRange: [0, 50],
      },
      {
        label: '联系电话',
        name: 'contact_phone',
        key: 'contact_phone',
        textRange: [0, 50],
      },
      {
        label: '手机号',
        name: 'mobile',
        key: 'mobile',
        textRange: [0, 50],
      },
      {
        label: '特长',
        name: 'speciality',
        key: 'speciality',
        textRange: [0, 50],
      },
      {
        label: '电子信箱',
        name: 'email',
        key: 'email',
        textRange: [0, 50],
      },
      {
        label: '主页地址',
        name: 'homepage',
        key: 'homepage',
        textRange: [0, 50],
      },
      {
        label: '通讯地址详细信息',
        name: 'contact_address_details',
        key: 'contact_address_details',
        textRange: [0, 50],
      },
      {
        label: '是否全日制特殊教育专业毕业',
        name: 'full_time_special_education_major_graduate',
        key: 'full_time_special_education_major_graduate',
        inputType: InputType.radio,
        required: true,
        renderOption: YES_NO,
      },
      {
        label: '是否受过学前教育专业培养培训',
        name: 'received_preschool_education_training',
        key: 'received_preschool_education_training',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      // {
      //   label: '是否为师范生',
      //   name: 'is_major_graduate',
      //   key: 'is_major_graduate',
      //   required: true,
      //   inputType: InputType.radio,
      //   renderOption: YES_NO,
      // },
      {
        label: '是否全日制师范类专业毕业',
        name: 'full_time_normal_major_graduate',
        key: 'full_time_normal_major_graduate',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '是否受过特教专业培训培养',
        name: 'received_special_education_training',
        key: 'received_special_education_training',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '是否有特殊教育从业证书',
        name: 'has_special_education_certificate',
        key: 'has_special_education_certificate',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '信息技术应用能力',
        name: 'information_technology_application_ability',
        key: 'information_technology_application_ability',
        required: true,
        inputType: InputType.select,
        renderOption: INFORMATION_APPLY_ABILITY,
      },
      {
        label: '是否属于免费(公费)师资生',
        name: 'free_normal_college_student',
        key: 'free_normal_college_student',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      // todo
      // {
      //   label: '是否属于免费(公费)师资生',
      //   name: 'free_normal_college_student',
      //   key: 'free_normal_college_student',
      //   required: true,
      //   inputType: 'radio',
      //   renderOption: YES_NO,
      // },
      {
        label: '是否参加基层服务项目',
        name: 'participated_in_basic_service_project',
        key: 'participated_in_basic_service_project',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '参加基层服务项目起始时间',
        name: 'basic_service_start_date',
        key: 'basic_service_start_date',
        inputType: InputType.date,
      },
      {
        label: '参加基层服务项目结束时间',
        name: 'basic_service_end_date',
        key: 'basic_service_end_date',
        inputType: InputType.date,
      },
      {
        label: '是否是特级教师',
        name: 'special_education_teacher',
        key: 'special_education_teacher',
        required: true,
        renderOption: YES_NO,
        inputType: InputType.radio,
      },
      {
        label: '是否"双师型"',
        name: 'dual_teacher',
        key: 'dual_teacher',
        required: true,
        renderOption: YES_NO,
        inputType: InputType.radio,
      },
      {
        label: '是否具备职业技能等级证书',
        name: 'has_occupational_skill_level_certificate',
        key: 'has_occupational_skill_level_certificate',
        required: true,
        renderOption: YES_NO,
        inputType: InputType.radio,
      },
      {
        label: '企业工作(实践)时长',
        name: 'enterprise_work_experience',
        key: 'enterprise_work_experience',
        required: true,
        textRange: [0, 20],
      },
      {
        label: '是否县级及以上骨干教师',
        name: 'county_level_backbone',
        key: 'county_level_backbone',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '是否心理健康教育教师',
        name: 'psychological_health_education_teacher',
        key: 'psychological_health_education_teacher',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '招聘方式',
        name: 'recruitment_method',
        key: 'recruitment_method',
        required: true,
        inputType: InputType.select,
        renderOption: RECRUITMENT_WAY,
      },
      {
        label: '教职工号',
        name: 'teacher_number',
        key: 'teacher_number',
        textRange: [0, 20],
      },
      {
        label: '接受过心理专业教育',
        name: 'accept_psychological_education',
        key: 'accept_psychological_education',
        textRange: [0, 20],
      },
      {
        label: '其他联系方式',
        name: 'other_contact_address_details',
        key: 'other_contact_address_details',
        textRange: [0, 50],
      },
      {
        label: '从教年月',
        name: 'from_education_date',
        key: 'from_education_date',
        inputType: InputType.date,
        inputProps: {
          picker: 'month',
        },
      },
      {
        label: '少数民族双语教师',
        name: 'minority_foreign_language_teacher',
        key: 'minority_foreign_language_teacher',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '是否行业导师',
        name: 'is_industry_teachers',
        key: 'is_industry_teachers',
        required: true,
        inputType: InputType.radio,
        renderOption: YES_NO,
      },
      {
        label: '教师资格证编号',
        name: 'teacher_qualification_certificate_number',
        key: 'teacher_qualification_certificate_number',
        textRange: [0, 50],
      },
      {
        label: '证书颁发日期',
        name: 'certificate_issue_date',
        key: 'certificate_issue_date',
        inputType: InputType.date,
        inputProps: {
          picker: 'month',
        },
      },
      {
        label: '所在部门',
        name: 'department',
        key: 'department',
        required: true,
        children: <Cascader />,
        inputType: InputType.children,
        renderOption: searchOrgs,
        formatValue: value => {
          if (value && typeof value === 'string') {
            return value.split(',');
          }
          return value;
        },
        formatSubmitValue: value => {
          if (value && value.length > 0) {
            return value.join(',');
          }
          return value;
        },
      },
      {
        label: '主要任课学段',
        name: 'main_teaching_level',
        key: 'main_teaching_level',
        required: true,
        inputType: InputType.select,
        renderOption: RECRUITMENT_WAY,
      },
      {
        label: '任教学科',
        name: 'teaching_discipline',
        key: 'teaching_discipline',
        required: true,
        inputType: InputType.select,
        renderOption: RECRUITMENT_WAY,
      },
      {
        label: '语种',
        name: 'language',
        key: 'language',
        required: true,
        inputType: InputType.select,
        renderOption: RECRUITMENT_WAY,
      },
      {
        label: '语言掌握程度',
        name: 'language_degree',
        key: 'language_degree',
        required: true,
        inputType: InputType.select,
        renderOption: RECRUITMENT_WAY,
      },
      {
        label: '语言证书名称',
        name: 'language_certificate_name',
        key: 'language_certificate_name',
        required: true,
        inputType: InputType.select,
        renderOption: RECRUITMENT_WAY,
      },
      {
        label: '第一课程',
        name: 'one_course',
        key: 'one_course',
        required: true,
        inputType: InputType.select,
        renderOption: RECRUITMENT_WAY,
      },
      {
        label: '第二课程',
        name: 'two_course',
        key: 'two_course',
        required: true,
        inputType: InputType.select,
        renderOption: RECRUITMENT_WAY,
      },
      {
        label: '第三课程',
        name: 'three_course',
        key: 'three_course',
        required: true,
        inputType: InputType.select,
        renderOption: RECRUITMENT_WAY,
      },
    ],
  },
];
// eslint-disable-next-line react/require-default-props
const Groups: FC<{
  title?: string;
  isEdit?: boolean;
  buttonList: React.ReactNode[];
  formValue?: any;
  api?: any;
}> = ({ title = '基本信息', isEdit = true, buttonList = [], formValue = {}, api = {} }) => {
  console.log('🚀 ~ formValue:', formValue);
  const navigate = useNavigate();
  const location = useLocation();
  const { id } = useParams();
  console.log('🚀 ~ location:', location);
  const [fromValues, setFromValues] = React.useState({ nationality: 'CN' });
  const [formV, setFormV] = React.useState(null);

  const buildValues = vals => {
    if (vals.department) {
      const departmentarr = vals.department.split(',');
      vals.org_id = departmentarr[departmentarr.length - 1];
    }
    return vals;
  };

  const buildBtns = () => {
    console.log('🚀 ~ buildBtns ~ isEdit:', isEdit);
    return isEdit
      ? [
          <Button type="primary" onClick={onSave}>
            保存
          </Button>,
        ]
      : buttonList;
  };
  React.useEffect(() => {
    if (Object.keys(formValue).length > 0) {
      const formTplInputs = {};
      formTpl[0].inputs
        .filter(v => v.inputType === 'radio')
        .forEach(it => {
          formTplInputs[it.name] = false;
        });
      setFromValues({
        ...fromValues,
        ...formTplInputs,
        ...formValue,
      });
    }
    console.log('🚀 ~ React.useEffect ~ formValue:', formValue);
  }, [formValue]);
  React.useEffect(() => {
    const formTplInputs = {};
    formTpl[0].inputs
      .filter(v => v.inputType === 'radio')
      .forEach(it => {
        formTplInputs[it.name] = false;
      });
    setFromValues({
      ...fromValues,
      ...formTplInputs,
    });
  }, []);

  const formatParams = values => {
    const params = {
      ...values,
      teacher_id: id,
      teacher_base_id: formValue?.teacher_base_id || location.state.teacher_base_id,
    };

    const formatTime = time => {
      if (!time) return undefined;
      return dayjs(time).format('YYYY-MM-DD');
    };

    params.basic_service_end_date = formatTime(values.basic_service_end_date);
    params.basic_service_start_date = formatTime(values.basic_service_start_date);

    params.enter_school_time = formatTime(values.enter_school_time);
    params.special_education_start_time = formatTime(values.special_education_start_time);
    params.start_working_date = formatTime(values.start_working_date);

    if (values.current_post_level && Array.isArray(values.current_post_level)) {
      params.current_post_level = params.current_post_level.join(',');
    }
    if (values.health_condition && Array.isArray(values.health_condition)) {
      params.health_condition = params.health_condition.join(',');
    }
    if (values.highest_education && Array.isArray(values.highest_education)) {
      params.highest_education = params.highest_education.join(',');
    }
    if (values.current_post_type && Array.isArray(values.current_post_type)) {
      params.current_post_type = params.current_post_type.join(',');
    }
    if (values.source_of_staff && Array.isArray(values.source_of_staff)) {
      params.source_of_staff = params.source_of_staff.join(',');
    }

    return params;
  };

  /** 基础信息提交 */
  const onSubmit = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    console.log('🚀 ~ onSubmit ~ values:', values);
    let params = formatParams(values);
    params = buildValues(params);
    const res = await api.submit(params);
    console.log('🚀 ~ handleAdd ~ res:', res);
    if (res.success) {
      // form.resetFields();
      message.success('提交成功');
      navigate(-1);
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  const onSave = async () => {
    let params = formatParams(formV.getFieldsValue());
    params = buildValues(params);
    const res = await api.save(params);
    console.log('🚀 ~ onSave ~ res:', res);
    if (res.success) {
      message.success('保存成功');
    }
  };

  return (
    <>
      <div className={`fixed-buttons ${styles.basic_panel}`}>
        <Row>
          <Col span={24}>
            <Suspense>
              <FormPanel
                template={formTpl}
                values={fromValues}
                btnsAlign={FormPanelBtnAlign.center}
                buttonsDisplay={FormPanelBtnDisplay.block}
                submitBtnText="提交"
                restBtnText="返回"
                buttons={buildBtns()}
                formStatus={isEdit ? FormPanelStatus.edit : FormPanelStatus.nonEdit}
                onLoad={(cntForm: FormPanelObject) => {
                  setFormV(cntForm);
                }}
                onReset={() => {
                  navigate(-1);
                }}
                onFinish={(formPanelObject: FormPanelObject) => {
                  onSubmit(formPanelObject);
                  return false;
                }}
              />
            </Suspense>
          </Col>
          {/* <Col span={isShowStep ? 6 : 0}>
            <Card style={{ height: 'calc(100% - 20px)', marginLeft: '10px' }}>
              <div className={styles.step_title}>处理详细</div>
              <Row className={styles.steps}>
                <Col className={styles.step}>20240401流程开始</Col>
                <Col className={styles.step}>20240401 ***学校张老师录入【提交申请】</Col>
                <Col className={styles.step}>20240401 ***老师录入【审核中】</Col>
                <Col className={styles.step}>20240401流程开始</Col>
                <Col className={styles.step}>20240401 ***学校张老师录入【提交申请】</Col>
                <Col className={styles.step}>20240401 ***老师录入【审核中】</Col>
                <Col className={styles.step}>20240401流程开始</Col>
                <Col className={styles.step}>20240401 ***学校张老师录入【提交申请】</Col>
                <Col className={styles.step}>20240401 ***老师录入【审核中】</Col>
                <Col className={styles.step}>20240401流程开始</Col>
                <Col className={styles.step}>20240401 ***学校张老师录入【提交申请】</Col>
                <Col className={styles.step}>20240401 ***老师录入【审核中】</Col>
              </Row>
            </Card>
          </Col> */}
        </Row>
      </div>
    </>
  );
};

Groups.defaultProps = {
  title: '基本信息',
  isEdit: true,
  formValue: {},
  api: {},
};

export default Groups;
